package com.kungfuhacking.wristbandpro.location.presenter;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.kungfuhacking.wristbandpro.base.bean.Basebean;
import com.kungfuhacking.wristbandpro.base.bean.RequestBean;
import com.kungfuhacking.wristbandpro.location.view.ISafeAddView;
import com.kungfuhacking.wristbandpro.login.activity.LoginActivity;
import com.kungfuhacking.wristbandpro.net.BaseNoTObserver;
import com.kungfuhacking.wristbandpro.net.RetrofitHttpUtil;
import com.kungfuhacking.wristbandpro.utils.LogUtil;

import io.reactivex.disposables.Disposable;


/**
 * 添加安全围栏
 * Created by Aaron on 17/5/8.
 */

public class ISafeAddPresenter extends LocationPresenter implements LocationSource, AMap.OnCameraChangeListener, AMapLocationListener {

    ISafeAddView iSafeAddView;
    private String TAG = getClass().getSimpleName();
    //    private AMapLocationClient aMapLocationClient;
    private AMapLocationClientOption mLocationOption;
    private boolean firstLocation = true;
    private LatLng mCurrentLatLng;

    public ISafeAddPresenter(ISafeAddView iSafeAddView) {
        this.iSafeAddView = iSafeAddView;
        firstLocation = true;
    }

    public LatLng getmCurrentLatLng() {
        return mCurrentLatLng;
    }

    public void setupMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.MAP_TYPE_NORMAL);
        //显示比例尺
        aMap.getUiSettings().setScaleControlsEnabled(true);
        aMap.setOnCameraChangeListener(this);
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setInterval(6000 * 1000);
        //设置定位监听
        mLocationClient.setLocationListener(this);
        //设置为高精度定位模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        mLocationClient.startLocation();
    }

    @Override
    public void deactivate() {

    }


    /**
     * 地图移动的时候回调
     */
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        mCurrentLatLng = new LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude);
        addMarker();
        addCircle(iSafeAddView.getRadius());
    }

    /**
     * 地图移动完成后回调
     */
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }

    public void addCircle(double radius) {

        LogUtil.d(TAG, "安全围栏的大小:" + radius);

        aMap.addCircle(new CircleOptions()
                .center(mCurrentLatLng)
                .strokeWidth(1f)
                .fillColor(FILL_COLOR)
                .strokeColor(STROKE_COLOR)
                .radius(radius));
    }

    public void addMarker() {
        aMap.clear();
        aMap.addMarker(iSafeAddView.getMarket(mCurrentLatLng));
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

        //如果是第一次定位则画默认的定位圈, 否则不需要
        if (firstLocation)
            firstLocation = false;
        else
            return;

        if (aMapLocation == null)
            return;

        if (aMapLocation.getErrorCode() == 0) {
            mCurrentLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            addMarker();
            addCircle(iSafeAddView.getRadius());//安全围栏圈
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCurrentLatLng, 17));//移动到location位置,并设置缩放比例
        }

    }

    /**
     * 根据半径改变地图大小
     *
     * @param Radius
     */
    public void changeScal(int Radius) {
        float scal = 17;
        if (Radius <= 300)
            scal = 17;
        else if (Radius > 300 && Radius <= 500)
            scal = 16;
        else if (Radius > 500 && Radius <= 800)
            scal = 15;
        else if (Radius > 800 && Radius <= 1000)
            scal = 14;

        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCurrentLatLng, scal));//移动到location位置,并设置缩放比例

    }

    /**
     * 添加安全区域
     *
     * @param id  当前老人的id
     * @param lat 坐标点
     * @param lng 坐标点
     */
    public void addSafeArea(String id, String lat, String lng) {

        if (TextUtils.isEmpty(iSafeAddView.getSafeName())) {
            iSafeAddView.showErr("请输入安全区域名称");
            return;
        }

        JSONObject j = new JSONObject();
        j.put("id", id);
        j.put("radius", iSafeAddView.getRadius() + "");
        j.put("token", iSafeAddView.getToken());
        j.put("latitude", lat);
        j.put("longitude", lng);
        j.put("areaName", iSafeAddView.getSafeName());

        RetrofitHttpUtil.getInstance().addSafeArea(new BaseNoTObserver<Basebean>() {
            @Override
            public void onHandleSuccess(Basebean basebean) {
                iSafeAddView.hideLoading();
                iSafeAddView.showErr("添加成功");
                iSafeAddView.finishPage();
            }

            @Override
            public void onHandleError(String message) {
                iSafeAddView.hideLoading();
                iSafeAddView.showErr(message);
            }

            @Override
            public void onReLogin(String message) {
                iSafeAddView.showErr(message);
                iSafeAddView.hideLoading();
                iSafeAddView.nextActivityWithSingleTask(LoginActivity.class);
            }

            @Override
            public void onSubscribe(Disposable d) {
                disposable = d;
                iSafeAddView.showLoading("创建中...");
            }
        }, new RequestBean().setData(j.toString()));

    }

    private Disposable disposable;

    public void clearRequest() {
        deactivate();
        if (disposable != null)
            disposable.dispose();
    }
}
